package com.alipay.sofa.demo.db.core.qps;

import com.alipay.sofa.demo.db.common.entity.StudentInfo;
import com.alipay.sofa.demo.db.common.entity.StudentInfoDTO;
import com.alipay.sofa.demo.db.common.exception.OperateDataException;
import com.alipay.sofa.demo.db.common.service.StudentInsertService;
import com.alipay.sofa.demo.db.common.tool.DataMockUtil;
import com.alipay.sofa.demo.db.core.consumer.StudentConsumer;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author Zhang Da
 * @Date 2020/2/14 22:30
 * @Version 1.0
 */

//@SpringBootApplication
//@ComponentScan("com.alipay.sofa.demo.db.core.impl")
//@MapperScan(basePackages = "com.alipay.sofa.demo.db.core.dao", annotationClass = Repository.class)
//@EnableScheduling
public class TpsApplication {

//    static StudentInsertService studentInsertService;
//
//    private static final Logger logger = LoggerFactory.getLogger(StudentConsumer.class);
//
//    private static volatile boolean stop = false;
//    private static final int THREAD_COUNT = 32;
//    private static int seconds = 60;
//    private static AtomicInteger successCount = new AtomicInteger();
//    private static AtomicInteger successInsertCount = new AtomicInteger();
//    private static long startTime;
//    private static long oldSuccessCount = 0;;
//    private static long oldInsertSuccessCount = 0;;
//
//    public static void main(String[] args) {
//        SpringApplication springApplication = new SpringApplication(TpsApplication.class);
//        ApplicationContext applicationContext = springApplication.run(args);
//
//        studentInsertService = (StudentInsertService) applicationContext
//                .getBean("studentInsertServiceImpl");
//
//        startTime = System.currentTimeMillis();
//        logger.info("---开始打印每秒请求成功数量--");
//        simulateTraffic();
//    }
//
//    private static void simulateTraffic() {
//        ExecutorService pool = new ThreadPoolExecutor(THREAD_COUNT, THREAD_COUNT*20, 300, TimeUnit.SECONDS,
//                                new LinkedBlockingQueue<>(THREAD_COUNT), Executors.defaultThreadFactory(),
//                                new ThreadPoolExecutor.AbortPolicy());
//        for(int j=0; j<THREAD_COUNT; j++){
//            pool.execute(()-> {
//                while (!stop) {
//                    try {
//                        List<StudentInfo> list = new ArrayList<StudentInfo>();
//                        int randomStudentNumber = DataMockUtil.getDistanceRandomNum(100, 200);
//                        for(int i=0; i<randomStudentNumber; i++){
//                            list.add(DataMockUtil.mockOneStudent());
//                        }
//                        successInsertCount.addAndGet(studentInsertService.insertStudents(list));
//                        successCount.addAndGet(1);
//                    } catch (OperateDataException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//            });
//        }
//        pool.shutdown();
//    }

//    @Scheduled(fixedDelay = 1000)
//    private void excuteTimer(){
//        if (!stop) {
//            //倒计时，每秒打印
//            long globalTotal = successCount.get();
//            long oneSecondTotal = globalTotal - oldSuccessCount;
//            oldSuccessCount = globalTotal;
//
//            long globalInsertTotal = successInsertCount.get();
//            long oneSecondInsertTotal = globalInsertTotal - oldInsertSuccessCount;
//            oldInsertSuccessCount = globalInsertTotal;
//
//            logger.info(seconds + " 插入次数 tps is: " + oneSecondTotal);
//            logger.info(seconds + " 插入条数 tps is: " + oneSecondInsertTotal);
//
//            if (seconds-- <= 1) {
//                stop = true;
//            }
//        }else{
//            //倒计时结束，打印统计数据，并退出
//            long cost = System.currentTimeMillis() - startTime;
//            logger.info(String.format("time cost: %d ms", cost));
//            logger.info(String.format("total: %d", successCount.get()));
//            logger.info(String.format("total seconds is %d, average insert times is %d", cost/1000, successCount.get()/(cost/1000)));
//            logger.info(String.format("total seconds is %d, average insert data's number is %d", cost/1000, successInsertCount.get()/(cost/1000)));
//            System.exit(0);
//        }
//
//    }
}
